package cn.cjlmonster.hyouka_assistant.ai

import android.Manifest
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Color
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
import cn.cjlmonster.hyouka_assistant.audio.AudioRecorder
import cn.cjlmonster.hyouka_assistant.base.BaseActivity
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 智能语音助手桥接
 *
 * @author cjl
 * @date 2025/5/20 17:51
 */
class AIAssistantBridge(
    val activity: BaseActivity<*>,
    val webView: WebView,
    val onClose: () -> Unit
) {

    val launcher = activity.registerForActivityResult(ActivityResultContracts.RequestPermission()) {
        if (it) {
            AudioRecorder.createRecord()
        }
    }

    var isIntercept = false

    init {
        inject()
        registerBackPress()
    }

    private var interceptJob: Job? = null
    private var interceptCount = 0

    @JavascriptInterface
    fun postMessage(message: String) =
        activity.lifecycleScope.solve(message) { id, method, param, callback ->
            when (method) {
                // 获取app信息
                "getAppInfo" -> activity.callMethod(
                    id, method, callback, mapOf(
                        "statusBarHeight" to activity.statusBarHeightDp,
                        "navigationBarHeight" to activity.navigationBarHeightDp
                    )
                )
                // 获取token
                "getToken" -> activity.callMethod(id, method, callback)
                // 刷新token
                "refreshToken" -> activity.callMethod(id, method, callback)
                // 返回上一页
                "goBack" -> webView.evaluate(id, callback) { activity.goBack() }
                // 拦截返回事件
                "interceptBackPress" -> webView.evaluate(id, callback) {
                    interceptJob?.cancel()
                    isIntercept = param.get("intercept").asBoolean
                    interceptCount = when (isIntercept) {
                        true -> interceptCount + 1
                        false -> interceptCount - 1
                    }
                    activity.runOnUiThread {
                        if (isIntercept) {
                            activity.window.navigationBarColor = Color.TRANSPARENT
                        } else if (interceptCount == 0) {
                            interceptJob = activity.lifecycleScope.launch {
                                delay(400)
                                activity.window.navigationBarColor = Color.WHITE
                            }
                        }
                    }
                }
                // 切换屏幕方向
                "changeOrientation" -> webView.evaluate(id, callback) {
                    activity.changeOrientation(param.get("isLandscape").asBoolean)
                }
                // 获取设备列表
                "getDeviceList" -> activity.callMethod(id, method, callback)
                // 修改设备别名
                "updateDeviceNickname" -> run {
                    val deviceCode = param.get("deviceCode").asString
                    val nickname = param.get("nickname").asString
                    activity.callMethod(
                        id,
                        method,
                        callback,
                        mapOf("deviceCode" to deviceCode, "nickname" to nickname)
                    )
                }
                // 保存图片到相册
                "saveImageToAlbum" -> {
                    val url = param.get("url").asString
                    activity.callMethod(
                        id,
                        method,
                        callback,
                        mapOf("url" to url)
                    )
                }
                // 复制文本
                "copyText" -> {
                    val text = param.get("text").asString
                    activity.callMethod(
                        id,
                        method,
                        callback,
                        mapOf("text" to text)
                    )
                }
                "toAddPage" -> activity.callMethod(id, method, callback)
                // 开始录音
                "startRecording" -> if (checkEnable()) {
                    activity.callMethod(id, method, callback)
                } else webView.evaluate(id, callback) {
                    put("result", false)
                }
                // 结束录音
                "stopRecording" -> activity.callMethod(id, method, callback)
                // 未实现方法
                else -> webView.evaluate(id, callback)
            }
        }
}

/**
 * 注入 JSBridge
 */
private fun AIAssistantBridge.inject() {
    webView.addJavascriptInterface(this, "app")
}

/**
 * 注册返回事件
 */
private fun AIAssistantBridge.registerBackPress() {
    activity.onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            if (isIntercept) return
            if (webView.canGoBack()) {
                webView.goBack()
                if (activity.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    activity.changeOrientation(false)
                }
            } else onClose.invoke()
        }
    })
}

/**
 * 检测语音功能是否可用
 */
private fun AIAssistantBridge.checkEnable(): Boolean {
    val isGrant = ActivityCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
    if (isGrant != PackageManager.PERMISSION_GRANTED) {
        launcher.launch(Manifest.permission.RECORD_AUDIO)
        return false
    }
    return true
}